package com.nondo.dean.auth.provider.impl;

import com.nondo.dean.auth.common.BusinessUtils;
import com.nondo.dean.auth.common.bean.AuthorityItem;
import com.nondo.dean.auth.domain.Authority;
import com.nondo.dean.auth.provider.AuthorityManager;
import com.nondo.dean.auth.service.AuthorityService;
import com.nondo.dean.auth.service.RoleAuthorityService;
import com.nondo.dean.common.web.Page;
import com.nondo.dean.common.web.Query;
import com.nondo.dean.common.web.View;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import static com.nondo.dean.auth.common.BusinessUtils.OPERA_REMOVE;

/**
 * @author slacrey
 * @since 2018/1/18
 */
@Service
public class AuthorityManagerImpl implements AuthorityManager, Serializable {

    private static final long serialVersionUID = -5809337602885587743L;

    @Autowired
    private AuthorityService authorityService;

    @Autowired
    private RoleAuthorityService roleAuthorityService;

    @Override
    public View<String> registerAuthority(AuthorityItem authority) {

        //查询出数据库中是否存在当前菜单
        authorityService.saveAuthority(BusinessUtils.toAuthority(authority));

        for (Map.Entry<String, List<Long>> entry : authority.getRoles().entrySet()) {
            if (OPERA_REMOVE.equalsIgnoreCase(entry.getKey())) {
                for (Long roleId : entry.getValue()) {
                    roleAuthorityService.deleteRoleAuthority(roleId, authority.getId());
                }
            } else {
                for (Long roleId : entry.getValue()) {
                    roleAuthorityService.saveRoleAuthority(roleId, authority.getId());
                }
            }
        }

        return View.ofOk("权限注册成功");

    }

    @Override
    public View<String> deleteAuthority(Long authorityId) {
        authorityService.deleteAuthority(authorityId);
        roleAuthorityService.deleteRoleAuthorityByAuthorityId(authorityId);
        return View.ofOk("权限删除成功");
    }

    @Override
    public View<Page<Authority>> findPageAuthority(Query<AuthorityItem> query) {

        Query<Authority> authorityQuery = new Query<>();
        authorityQuery.setPage(query.getPage());
        authorityQuery.setSize(query.getSize());
        authorityQuery.setData(BusinessUtils.toAuthority(query.getData()));

        return View.ofOk(authorityService.findPageAuthority(authorityQuery));
    }

    @Override
    public View<Authority> findAuthorityById(Long authorityId) {

        Authority authority = authorityService.findByAuthorityId(authorityId);
        if (authority == null) {
            return View.ofError("权限配置不存在");
        }
        return View.ofOk(authority);
    }

}
